package com.liu.stockmarket.ui.datacenter.ui.quotation

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.XAxis.XAxisPosition
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.liu.stockmarket.BaseFragment
import com.liu.stockmarket.R
import com.liu.stockmarket.StockMarketApplication
import com.liu.stockmarket.databinding.FragmentNewBondBinding
import com.liu.stockmarket.databinding.FragmentQuotationBinding
import com.liu.stockmarket.model.QuotationResult
import com.liu.stockmarket.mpchart.MyYAxisRenderer
import com.liu.stockmarket.mpchart.QuotationBarChartRenderer
import com.liu.stockmarket.mpchart.QuotationDataSet
import com.liu.stockmarket.ui.datacenter.DataCenterViewModel
import com.liu.stockmarket.ui.datacenter.ui.main.PlaceholderFragment
import com.liu.stockmarket.ui.weight.TipMarkerView
import com.liu.stockmarket.utils.MD
import com.liu.stockmarket.utils.getString
import java.math.BigDecimal
import java.math.MathContext
import java.time.LocalDateTime
import java.time.ZoneOffset

class QuotationFragment : BaseFragment() {
    private lateinit var viewModel: DataCenterViewModel

    private var _binding: FragmentQuotationBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private val rawData: MutableList<QuotationResult.Data.Diff> = mutableListOf()

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentQuotationBinding.inflate(inflater, container, false)
        val root: View = binding.root
        val application = this.requireActivity().application as StockMarketApplication
        viewModel = ViewModelProvider(
            this,
            DataCenterViewModel.DataCenterViewModelFactory(application.easyMoneyRepository)
        ).get(DataCenterViewModel::class.java)
        viewModel.getQuotation()

        initBarChart()

        return root
    }

    private fun setData(data: QuotationResult) {
        val diff = data.data.diff
        rawData.clear()
        rawData.addAll(diff)

        val barEntrys =
            diff.mapIndexed { index, d -> BarEntry(index.toFloat(), d.money.toFloat()) }

        val barDataSet = QuotationDataSet(barEntrys, "")
        barDataSet.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                return getXText(value)
            }
        }
        barDataSet.colors = listOf(requireContext().getColor(R.color.up),requireContext().getColor(R.color.down))
        val barData = BarData(barDataSet)
        binding.barChart.data = barData
        binding.barChart.invalidate()

    }


    private fun initBarChart() {
        val chart = binding.barChart
//        chart.setOnChartValueSelectedListener(this)
        // chart.setHighlightEnabled(false);

        // chart.setHighlightEnabled(false);

//        chart.renderer = QuotationBarChartRenderer(
//            requireContext(),
//            chart,
//            chart.animator,
//            chart.viewPortHandler
//        )
        chart.setDrawBarShadow(false)
        val description = Description()


        description.isEnabled =true
        description.text = "单位（亿元）"
        description.textColor = requireContext().getColor(R.color.black)
        chart.description = description


        chart.setDrawValueAboveBar(true)
        chart.isScaleYEnabled = false


        // if more than 60 entries are displayed in the chart, no values will be
        // drawn

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        chart.setMaxVisibleValueCount(60)

        // scaling can now only be done on x- and y-axis separately

        // scaling can now only be done on x- and y-axis separately
        chart.setPinchZoom(false)


        // draw shadows for each bar that show the maximum value
        // chart.setDrawBarShadow(true);


        // draw shadows for each bar that show the maximum value
        // chart.setDrawBarShadow(true);
        chart.setDrawGridBackground(false)

        val xl: XAxis = chart.xAxis
        xl.position = XAxisPosition.BOTTOM
        xl.setDrawAxisLine(true)
        xl.setDrawGridLines(false)
        xl.setLabelCount(10,false)
        xl.textColor = requireContext().getColor(R.color.black)

//        xl.granularity = 10f

        xl.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                if (value<0 || value >= rawData.size) {
                    return ""
                }
                return rawData[value.toInt()].name
            }
        }
        xl.labelRotationAngle = -90f

        val yl: YAxis = chart.axisLeft
        yl.setDrawAxisLine(true)
        yl.setDrawGridLines(true)



        yl.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                return getXText(value)
            }
        }
//        yl.setInverted(true);

        //        yl.setInverted(true);
        val yr: YAxis = chart.axisRight
        yr.isEnabled = false
        yr.setDrawAxisLine(false)
//        yr.setInverted(true);

        //        yr.setInverted(true);
        chart.setFitBars(true)
        chart.animateY(2500)

        chart.rendererLeftYAxis = MyYAxisRenderer(
            requireContext(),
            chart.viewPortHandler,
            chart.axisLeft,
            chart.getTransformer(YAxis.AxisDependency.LEFT)
        )

        val tipMarkerView = TipMarkerView(requireContext()) {
            return@TipMarkerView "${rawData[it.x.toInt()].name}\n${getXText(it.y)}亿"
        }
        tipMarkerView.chartView = chart
        chart.setDrawMarkers(true)
        chart.marker = tipMarkerView


        val l: Legend = chart.legend
        l.isEnabled=false
        l.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        l.orientation = Legend.LegendOrientation.HORIZONTAL
        l.setDrawInside(false)
        l.formSize = 8f
        l.xEntrySpace = 4f

    }

    private fun getXText(xValue: Float): String {
        val bigDecimal = BigDecimal(xValue.toString(), MathContext.DECIMAL32).setScale(
            5,
            BigDecimal.ROUND_CEILING
        )


        return (bigDecimal / BigDecimal("100000000").setScale(
            5,
            BigDecimal.ROUND_CEILING
        )).getString(2)
    }

    override fun listener() {
    }

    override fun observer() {
        viewModel.quotationResult.observe(this) {
            setData(it)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

    companion object {
        @JvmStatic
        fun newInstance(): QuotationFragment {
            return QuotationFragment()
        }

    }
}